Interface 类
Interface 类是 Gradio 中最基础和常用的类,它允许您通过简单的 API 快速为任何 Python 函数创建用户界面。
基本用法
Interface 类的基本语法如下:
python
import gradio as gr
def function_name(*args):
# 处理输入
return output
demo = gr.Interface(
fn=function_name, # 要创建界面的函数
inputs=[...], # 输入组件
outputs=[...], # 输出组件
examples=[...], # 可选:示例输入
cache_examples=True, # 可选:缓存示例结果
title="...", # 可选:界面标题
description="...", # 可选:界面描述
article="...", # 可选:界面底部的额外说明文本
theme="default", # 可选:界面主题
css="...." # 可选:自定义 CSS
)
demo.launch()
主要参数详解
fn
fn
参数是 Interface 的核心,它是您想要创建界面的 Python 函数。此函数可以是任何接受某些输入并返回某些输出的函数。
python
def greet(name):
return "您好," + name + "!"
demo = gr.Interface(fn=greet, inputs="text", outputs="text")
inputs
inputs
参数定义了函数输入参数对应的界面组件。可以是单个组件或组件列表(对应多个输入参数)。
python
# 单个输入
inputs = gr.Textbox(label="姓名")
# 多个输入
inputs = [
gr.Textbox(label="姓名"),
gr.Number(label="年龄")
]
# 使用简写形式
inputs = ["text", "number"] # 等同于上面的写法
常用的输入组件包括:
Textbox
/"text"
:文本框Number
/"number"
:数字输入Slider
:滑动条Checkbox
/"checkbox"
:复选框Radio
/"radio"
:单选按钮Dropdown
/"dropdown"
:下拉列表Image
/"image"
:图像上传Audio
/"audio"
:音频上传Video
/"video"
:视频上传File
/"file"
:文件上传
outputs
outputs
参数定义了函数返回值对应的界面组件。可以是单个组件或组件列表(对应多个返回值)。
python
# 单个输出
outputs = gr.Textbox(label="问候语")
# 多个输出
outputs = [
gr.Textbox(label="问候语"),
gr.Image(label="头像")
]
# 使用简写形式
outputs = ["text", "image"] # 等同于上面的写法
常用的输出组件包括:
Textbox
/"text"
:文本框Number
/"number"
:数字Label
/"label"
:标签(适用于分类结果)Image
/"image"
:图像Audio
/"audio"
:音频Video
/"video"
:视频DataFrame
/"dataframe"
:数据表格JSON
/"json"
:JSON 数据HTML
/"html"
:HTML 内容Markdown
/"markdown"
:Markdown 内容
examples
examples
参数允许您为界面提供示例输入,用户可以点击这些示例快速测试应用。
python
def greeting(name, age):
return f"你好,{name}!你已经 {age} 岁了。"
demo = gr.Interface(
fn=greeting,
inputs=["text", "number"],
outputs="text",
examples=[
["张三", 25],
["李四", 30],
["王五", 22]
]
)
title 和 description
title
和 description
参数允许您为界面添加标题和描述文本:
python
demo = gr.Interface(
fn=my_function,
inputs=...,
outputs=...,
title="我的图像分类器",
description="上传图像,获取分类结果"
)
article
article
参数允许您在界面底部添加更长的 Markdown 格式的说明文本:
python
article = """
## 使用说明
1. 上传一张猫或狗的图像
2. 点击"提交"按钮
3. 查看分类结果
本分类器使用了 ResNet50 模型,在 ImageNet 数据集上预训练。
"""
demo = gr.Interface(..., article=article)
示例应用
图像分类器
python
import gradio as gr
import numpy as np
from PIL import Image
def classify_image(img):
# 这里通常是您的模型预测代码
# 为简化示例,我们返回随机结果
classes = ["猫", "狗", "鸟", "鱼", "其他"]
confidences = np.random.rand(5)
confidences = confidences / np.sum(confidences)
return {classes[i]: float(confidences[i]) for i in range(len(classes))}
demo = gr.Interface(
fn=classify_image,
inputs=gr.Image(type="pil"),
outputs=gr.Label(num_top_classes=3),
title="简单图像分类器",
description="上传一张图像,查看分类结果",
examples=["example_image1.jpg", "example_image2.jpg"]
)
demo.launch()
文本到图像生成器
python
import gradio as gr
import numpy as np
from PIL import Image
def text_to_image(text, style):
# 这里通常是您的模型生成代码
# 为简化示例,我们生成随机彩色图像
img = np.random.randint(0, 255, (256, 256, 3), dtype=np.uint8)
return Image.fromarray(img)
demo = gr.Interface(
fn=text_to_image,
inputs=[
gr.Textbox(label="描述文本", placeholder="一只蓝色的猫..."),
gr.Radio(["写实风格", "卡通风格", "油画风格"], label="图像风格")
],
outputs=gr.Image(label="生成的图像"),
title="文本到图像生成器",
description="输入描述和风格,生成相应的图像"
)
demo.launch()
界面配置和定制
预测时事件
您可以通过设置以下参数来控制预测行为:
python
demo = gr.Interface(
...,
live=True, # 实时更新结果(无需点击提交)
interpretation="default", # 启用模型解释功能
batch=True, # 启用批处理模式
max_batch_size=16 # 批处理的最大批次大小
)
样式和主题
您可以使用以下参数来定制界面外观:
python
demo = gr.Interface(
...,
theme=gr.themes.Base(), # 使用预定义主题
css=".gradio-container {background-color: lightblue}" # 自定义 CSS
)
身份验证
您可以为您的应用添加简单的身份验证:
python
demo = gr.Interface(...)
demo.launch(auth=("用户名", "密码"))
前端 JavaScript 事件
您可以使用 js
参数添加自定义 JavaScript:
python
js = """
function(x) {
console.log("输入值:", x);
return x;
}
"""
demo = gr.Interface(..., js=js)
总结
Interface 类提供了一种快速为 Python 函数创建交互式 Web 界面的方法,适用于简单的单功能应用。它封装了许多常见的 UI 模式,无需您了解 Web 开发知识。
对于更复杂的界面和应用程序流程,您可能需要使用 Blocks API,它提供了更灵活的界面布局和组件交互控制。